import React, { useRef, useEffect, useState, useCallback } from 'react';
import * as THREE from 'three';
import { OrbitControls } from 'three-stdlib';
import { Modal, Descriptions, Tag, Statistic, Card, Row, Col, Progress, Table, Spin } from 'antd';
import {
  DatabaseOutlined,
  HomeOutlined,
  CheckCircleOutlined,
  WarningOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';

// 电梯信息接口
interface ElevatorData {
  id: string;
  type: 'passenger' | 'freight' | 'emergency';
  status: 'normal' | 'maintenance' | 'error';
  floors: number[]; // 服务楼层
}

// 设备信息接口
interface DeviceData {
  id: string;
  name: string;
  type: 'elevator' | 'hvac' | 'security' | 'lighting' | 'fire_safety' | 'access_control';
  buildingId: string;
  buildingName: string;
  status: 'online' | 'offline' | 'maintenance' | 'error';
  location: string;
  lastMaintenance: string;
  nextMaintenance: string;
  manufacturer: string;
  model: string;
  installDate: string;
  energyConsumption?: number; // kWh
  operatingHours?: number;
}

// 楼宇数据接口
interface BuildingData {
  id: string;
  name: string;
  position: { x: number; y: number; z: number };
  floors: number;
  type: 'residential' | 'commercial' | 'office' | 'mixed';
  status: 'normal' | 'medium' | 'low';
  occupancy: number; // 入住率 0-100
  elevators: ElevatorData[]; // 电梯信息
}

// 华发二期模拟数据 - 根据Dashboard3D.tsx中的真实数据
const mockBuildingsDataPhase2: BuildingData[] = [
  {
    id: '7',
    name: '华发二期A座',
    position: { x: -60, y: 0, z: -40 },
    floors: 30,
    type: 'office',
    status: 'normal',
    occupancy: 88,
    elevators: [
      { id: 'A1', type: 'passenger', status: 'normal', floors: Array.from({length: 30}, (_, i) => i + 1) },
      { id: 'A2', type: 'passenger', status: 'normal', floors: Array.from({length: 30}, (_, i) => i + 1) }
    ]
  },
  {
    id: '8',
    name: '华发二期B座',
    position: { x: -30, y: 0, z: -40 },
    floors: 28,
    type: 'office',
    status: 'normal',
    occupancy: 92,
    elevators: [
      { id: 'B1', type: 'passenger', status: 'normal', floors: Array.from({length: 28}, (_, i) => i + 1) },
      { id: 'B2', type: 'passenger', status: 'maintenance', floors: Array.from({length: 28}, (_, i) => i + 1) }
    ]
  },
  {
    id: '9',
    name: '华发二期C座',
    position: { x: 0, y: 0, z: -40 },
    floors: 32,
    type: 'office',
    status: 'medium',
    occupancy: 78,
    elevators: [
      { id: 'C1', type: 'passenger', status: 'normal', floors: Array.from({length: 32}, (_, i) => i + 1) },
      { id: 'C2', type: 'passenger', status: 'error', floors: Array.from({length: 32}, (_, i) => i + 1) },
      { id: 'C3', type: 'freight', status: 'normal', floors: [1, 2, 3, 4, 5, 10, 15, 20, 25, 30, 32] }
    ]
  },
  {
    id: '10',
    name: '华发二期D座',
    position: { x: 30, y: 0, z: -40 },
    floors: 35,
    type: 'office',
    status: 'normal',
    occupancy: 95,
    elevators: [
      { id: 'D1', type: 'passenger', status: 'normal', floors: Array.from({length: 35}, (_, i) => i + 1) },
      { id: 'D2', type: 'passenger', status: 'normal', floors: Array.from({length: 35}, (_, i) => i + 1) },
      { id: 'D3', type: 'freight', status: 'normal', floors: [1, 2, 5, 10, 15, 20, 25, 30, 35] },
      { id: 'D4', type: 'emergency', status: 'normal', floors: Array.from({length: 35}, (_, i) => i + 1) }
    ]
  },
  {
    id: '11',
    name: '华发二期E座',
    position: { x: -45, y: 0, z: 10 },
    floors: 26,
    type: 'residential',
    status: 'normal',
    occupancy: 88,
    elevators: [
      { id: 'E1', type: 'passenger', status: 'normal', floors: Array.from({length: 26}, (_, i) => i + 1) },
      { id: 'E2', type: 'passenger', status: 'normal', floors: Array.from({length: 26}, (_, i) => i + 1) },
      { id: 'E3', type: 'freight', status: 'maintenance', floors: [1, 5, 10, 15, 20, 26] }
    ]
  },
  {
    id: '12',
    name: '华发二期F座',
    position: { x: -15, y: 0, z: 10 },
    floors: 24,
    type: 'residential',
    status: 'low',
    occupancy: 65,
    elevators: [
      { id: 'F1', type: 'passenger', status: 'normal', floors: Array.from({length: 24}, (_, i) => i + 1) },
      { id: 'F2', type: 'passenger', status: 'normal', floors: Array.from({length: 24}, (_, i) => i + 1) },
      { id: 'F3', type: 'passenger', status: 'error', floors: Array.from({length: 24}, (_, i) => i + 1) },
      { id: 'F4', type: 'freight', status: 'normal', floors: [1, 2, 5, 10, 15, 20, 24] },
      { id: 'F5', type: 'emergency', status: 'normal', floors: Array.from({length: 24}, (_, i) => i + 1) }
    ]
  },
  {
    id: '13',
    name: '华发二期G座',
    position: { x: 15, y: 0, z: 10 },
    floors: 28,
    type: 'residential',
    status: 'normal',
    occupancy: 82,
    elevators: [
      { id: 'G1', type: 'passenger', status: 'normal', floors: Array.from({length: 28}, (_, i) => i + 1) },
      { id: 'G2', type: 'passenger', status: 'normal', floors: Array.from({length: 28}, (_, i) => i + 1) }
    ]
  },
  {
    id: '14',
    name: '华发二期H座',
    position: { x: 45, y: 0, z: 10 },
    floors: 30,
    type: 'residential',
    status: 'medium',
    occupancy: 75,
    elevators: [
      { id: 'H1', type: 'passenger', status: 'normal', floors: Array.from({length: 30}, (_, i) => i + 1) },
      { id: 'H2', type: 'passenger', status: 'maintenance', floors: Array.from({length: 30}, (_, i) => i + 1) }
    ]
  },
  {
    id: '15',
    name: '华发二期I座',
    position: { x: -30, y: 0, z: 50 },
    floors: 22,
    type: 'residential',
    status: 'normal',
    occupancy: 90,
    elevators: [
      { id: 'I1', type: 'passenger', status: 'normal', floors: Array.from({length: 22}, (_, i) => i + 1) },
      { id: 'I2', type: 'passenger', status: 'normal', floors: Array.from({length: 22}, (_, i) => i + 1) }
    ]
  },
  {
    id: '16',
    name: '华发二期J座',
    position: { x: 0, y: 0, z: 50 },
    floors: 25,
    type: 'residential',
    status: 'normal',
    occupancy: 87,
    elevators: [
      { id: 'J1', type: 'passenger', status: 'normal', floors: Array.from({length: 25}, (_, i) => i + 1) },
      { id: 'J2', type: 'passenger', status: 'normal', floors: Array.from({length: 25}, (_, i) => i + 1) }
    ]
  },
  {
    id: '17',
    name: '华发二期K座',
    position: { x: 30, y: 0, z: 50 },
    floors: 27,
    type: 'residential',
    status: 'low',
    occupancy: 68,
    elevators: [
      { id: 'K1', type: 'passenger', status: 'normal', floors: Array.from({length: 27}, (_, i) => i + 1) },
      { id: 'K2', type: 'passenger', status: 'error', floors: Array.from({length: 27}, (_, i) => i + 1) }
    ]
  },
  {
    id: '18',
    name: '华发二期L座',
    position: { x: 60, y: 0, z: 50 },
    floors: 29,
    type: 'residential',
    status: 'normal',
    occupancy: 85,
    elevators: [
      { id: 'L1', type: 'passenger', status: 'normal', floors: Array.from({length: 29}, (_, i) => i + 1) },
      { id: 'L2', type: 'passenger', status: 'normal', floors: Array.from({length: 29}, (_, i) => i + 1) }
    ]
  }
];

const mockDevicesDataPhase2: DeviceData[] = [
  // 华发二期A座设备
  { id: 'DEV022', name: '电梯A1', type: 'elevator', buildingId: '7', buildingName: '华发二期A座', status: 'online', location: 'A座东侧', lastMaintenance: '2024-01-15', nextMaintenance: '2024-04-15', manufacturer: '奥的斯', model: 'Gen2-MR', installDate: '2021-03-10', operatingHours: 6760 },
  { id: 'DEV023', name: '电梯A2', type: 'elevator', buildingId: '7', buildingName: '华发二期A座', status: 'online', location: 'A座西侧', lastMaintenance: '2024-01-15', nextMaintenance: '2024-04-15', manufacturer: '奥的斯', model: 'Gen2-MR', installDate: '2021-03-10', operatingHours: 6650 },
  
  // 华发二期B座设备
  { id: 'DEV024', name: '客梯B1', type: 'elevator', buildingId: '8', buildingName: '华发二期B座', status: 'maintenance', location: 'B座1号梯', lastMaintenance: '2024-02-10', nextMaintenance: '2024-05-10', manufacturer: '三菱', model: 'NEXIEZ-MRL', installDate: '2021-08-20', operatingHours: 7500 },
  { id: 'DEV025', name: '货梯B2', type: 'elevator', buildingId: '8', buildingName: '华发二期B座', status: 'online', location: 'B座货梯', lastMaintenance: '2024-01-25', nextMaintenance: '2024-04-25', manufacturer: '三菱', model: 'ELENESSA', installDate: '2021-08-20', operatingHours: 6800 },
  
  // 华发二期C座设备
  { id: 'DEV026', name: '高速电梯C1', type: 'elevator', buildingId: '9', buildingName: '华发二期C座', status: 'online', location: 'C座1号梯', lastMaintenance: '2024-02-05', nextMaintenance: '2024-05-05', manufacturer: '日立', model: 'NEXWAY', installDate: '2022-05-15', operatingHours: 4200 },
  { id: 'DEV027', name: '高速电梯C2', type: 'elevator', buildingId: '9', buildingName: '华发二期C座', status: 'error', location: 'C座2号梯', lastMaintenance: '2024-01-10', nextMaintenance: '2024-04-10', manufacturer: '日立', model: 'NEXWAY', installDate: '2022-05-15', operatingHours: 4150 },
  
  // 华发二期D座设备
  { id: 'DEV028', name: '客梯D1', type: 'elevator', buildingId: '10', buildingName: '华发二期D座', status: 'online', location: 'D座1号梯', lastMaintenance: '2024-02-12', nextMaintenance: '2024-05-12', manufacturer: '蒂森克虏伯', model: 'synergy', installDate: '2022-11-10', operatingHours: 3600 },
  { id: 'DEV029', name: '客梯D2', type: 'elevator', buildingId: '10', buildingName: '华发二期D座', status: 'online', location: 'D座2号梯', lastMaintenance: '2024-02-12', nextMaintenance: '2024-05-12', manufacturer: '蒂森克虏伯', model: 'synergy', installDate: '2022-11-10', operatingHours: 3450 },
  
  // 华发二期E座设备
  { id: 'DEV030', name: '高速电梯E1', type: 'elevator', buildingId: '11', buildingName: '华发二期E座', status: 'online', location: 'E座1号梯', lastMaintenance: '2024-02-08', nextMaintenance: '2024-05-08', manufacturer: '迅达', model: '7000', installDate: '2023-01-20', operatingHours: 2800 },
  { id: 'DEV031', name: '高速电梯E2', type: 'elevator', buildingId: '11', buildingName: '华发二期E座', status: 'online', location: 'E座2号梯', lastMaintenance: '2024-02-08', nextMaintenance: '2024-05-08', manufacturer: '迅达', model: '7000', installDate: '2023-01-20', operatingHours: 2750 },
  
  // 华发二期F座设备
  { id: 'DEV032', name: '超高速电梯F1', type: 'elevator', buildingId: '12', buildingName: '华发二期F座', status: 'online', location: 'F座1号梯', lastMaintenance: '2024-02-22', nextMaintenance: '2024-05-22', manufacturer: '东芝', model: 'SPACEL-GR', installDate: '2023-03-15', operatingHours: 2200 },
  { id: 'DEV033', name: '超高速电梯F2', type: 'elevator', buildingId: '12', buildingName: '华发二期F座', status: 'online', location: 'F座2号梯', lastMaintenance: '2024-02-22', nextMaintenance: '2024-05-22', manufacturer: '东芝', model: 'SPACEL-GR', installDate: '2023-03-15', operatingHours: 2150 },
  
  // 华发二期G座设备
  { id: 'DEV034', name: '电梯G1', type: 'elevator', buildingId: '13', buildingName: '华发二期G座', status: 'online', location: 'G座1号梯', lastMaintenance: '2024-02-25', nextMaintenance: '2024-05-25', manufacturer: '奥的斯', model: 'Gen2-MR', installDate: '2023-06-10', operatingHours: 1800 },
  { id: 'DEV035', name: '电梯G2', type: 'elevator', buildingId: '13', buildingName: '华发二期G座', status: 'online', location: 'G座2号梯', lastMaintenance: '2024-02-25', nextMaintenance: '2024-05-25', manufacturer: '奥的斯', model: 'Gen2-MR', installDate: '2023-06-10', operatingHours: 1750 },
  
  // 华发二期H座设备
  { id: 'DEV036', name: '电梯H1', type: 'elevator', buildingId: '14', buildingName: '华发二期H座', status: 'online', location: 'H座1号梯', lastMaintenance: '2024-03-01', nextMaintenance: '2024-06-01', manufacturer: '三菱', model: 'NEXIEZ-MRL', installDate: '2023-07-15', operatingHours: 1600 },
  { id: 'DEV037', name: '电梯H2', type: 'elevator', buildingId: '14', buildingName: '华发二期H座', status: 'maintenance', location: 'H座2号梯', lastMaintenance: '2024-03-01', nextMaintenance: '2024-06-01', manufacturer: '三菱', model: 'NEXIEZ-MRL', installDate: '2023-07-15', operatingHours: 1550 },
  
  // 华发二期I座设备
  { id: 'DEV038', name: '电梯I1', type: 'elevator', buildingId: '15', buildingName: '华发二期I座', status: 'online', location: 'I座1号梯', lastMaintenance: '2024-03-05', nextMaintenance: '2024-06-05', manufacturer: '日立', model: 'NEXWAY', installDate: '2023-08-20', operatingHours: 1400 },
  { id: 'DEV039', name: '电梯I2', type: 'elevator', buildingId: '15', buildingName: '华发二期I座', status: 'online', location: 'I座2号梯', lastMaintenance: '2024-03-05', nextMaintenance: '2024-06-05', manufacturer: '日立', model: 'NEXWAY', installDate: '2023-08-20', operatingHours: 1350 },
  
  // 华发二期J座设备
  { id: 'DEV040', name: '电梯J1', type: 'elevator', buildingId: '16', buildingName: '华发二期J座', status: 'online', location: 'J座1号梯', lastMaintenance: '2024-03-10', nextMaintenance: '2024-06-10', manufacturer: '蒂森克虏伯', model: 'synergy', installDate: '2023-09-25', operatingHours: 1200 },
  { id: 'DEV041', name: '电梯J2', type: 'elevator', buildingId: '16', buildingName: '华发二期J座', status: 'online', location: 'J座2号梯', lastMaintenance: '2024-03-10', nextMaintenance: '2024-06-10', manufacturer: '蒂森克虏伯', model: 'synergy', installDate: '2023-09-25', operatingHours: 1150 },
  
  // 华发二期K座设备
  { id: 'DEV042', name: '电梯K1', type: 'elevator', buildingId: '17', buildingName: '华发二期K座', status: 'online', location: 'K座1号梯', lastMaintenance: '2024-03-15', nextMaintenance: '2024-06-15', manufacturer: '迅达', model: '7000', installDate: '2023-10-30', operatingHours: 1000 },
  { id: 'DEV043', name: '电梯K2', type: 'elevator', buildingId: '17', buildingName: '华发二期K座', status: 'error', location: 'K座2号梯', lastMaintenance: '2024-03-15', nextMaintenance: '2024-06-15', manufacturer: '迅达', model: '7000', installDate: '2023-10-30', operatingHours: 950 },
  
  // 华发二期L座设备
  { id: 'DEV044', name: '电梯L1', type: 'elevator', buildingId: '18', buildingName: '华发二期L座', status: 'online', location: 'L座1号梯', lastMaintenance: '2024-03-20', nextMaintenance: '2024-06-20', manufacturer: '东芝', model: 'SPACEL-GR', installDate: '2023-11-15', operatingHours: 800 },
  { id: 'DEV045', name: '电梯L2', type: 'elevator', buildingId: '18', buildingName: '华发二期L座', status: 'online', location: 'L座2号梯', lastMaintenance: '2024-03-20', nextMaintenance: '2024-06-20', manufacturer: '东芝', model: 'SPACEL-GR', installDate: '2023-11-15', operatingHours: 750 }
];

const Phase2View: React.FC = () => {
  const mountRef = useRef<HTMLDivElement>(null);
  const sceneRef = useRef<THREE.Scene | null>(null);
  const rendererRef = useRef<THREE.WebGLRenderer | null>(null);
  const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);
  const controlsRef = useRef<OrbitControls | null>(null);
  const animationIdRef = useRef<number | undefined>(undefined);
  const startLoopRef = useRef<(() => void) | null>(null);
  
  const [isLoading, setIsLoading] = useState(true);
  const [selectedDevice, setSelectedDevice] = useState<DeviceData | null>(null);
  const [deviceModalVisible, setDeviceModalVisible] = useState(false);
  const [selectedBuilding, setSelectedBuilding] = useState<BuildingData | null>(null);
  const [buildingModalVisible, setBuildingModalVisible] = useState(false);

  // 获取楼宇颜色
  const getBuildingColor = useCallback((building: BuildingData): number => {
    switch (building.status) {
      case 'normal': return 0x4CAF50; // 绿色
      case 'medium': return 0xFF9800; // 橙色
      case 'low': return 0xF44336; // 红色
      default: return 0x9E9E9E; // 灰色
    }
  }, []);

  // 获取楼宇类型颜色
  const getBuildingTypeColor = useCallback((type: string): number => {
    switch (type) {
      case 'residential': return 0x2196F3; // 蓝色
      case 'commercial': return 0x9C27B0; // 紫色
      case 'office': return 0x607D8B; // 蓝灰色
      case 'mixed': return 0x795548; // 棕色
      default: return 0x9E9E9E;
    }
  }, []);

  // 获取电梯颜色
  const getElevatorColor = useCallback((elevator: ElevatorData): number => {
    switch (elevator.status) {
      case 'normal': return 0x00FF00; // 绿色
      case 'maintenance': return 0xFFFF00; // 黄色
      case 'error': return 0xFF0000; // 红色
      default: return 0x808080;
    }
  }, []);

  // 创建设备3D图标
  const createDeviceIcon = useCallback((device: DeviceData): THREE.Group => {
    const iconGroup = new THREE.Group();
    
    // 根据设备类型创建不同的3D图标
    switch (device.type) {
      case 'elevator':
        // 电梯图标 - 立方体带箭头
        const elevatorGeometry = new THREE.BoxGeometry(0.8, 1.2, 0.8);
        const elevatorMaterial = new THREE.MeshLambertMaterial({ 
          color: device.status === 'online' ? 0x4CAF50 : 
                 device.status === 'maintenance' ? 0xFF9800 : 0xF44336
        });
        const elevatorMesh = new THREE.Mesh(elevatorGeometry, elevatorMaterial);
        
        // 电梯门
        const doorGeometry = new THREE.PlaneGeometry(0.6, 1.0);
        const doorMaterial = new THREE.MeshLambertMaterial({ color: 0x666666 });
        const doorMesh = new THREE.Mesh(doorGeometry, doorMaterial);
        doorMesh.position.z = 0.41;
        
        iconGroup.add(elevatorMesh);
        iconGroup.add(doorMesh);
        break;
        
      case 'hvac':
        // HVAC图标 - 圆柱体带风扇
        const hvacGeometry = new THREE.CylinderGeometry(0.6, 0.6, 0.4, 8);
        const hvacMaterial = new THREE.MeshLambertMaterial({ 
          color: device.status === 'online' ? 0x2196F3 : 
                 device.status === 'maintenance' ? 0xFF9800 : 0xF44336
        });
        const hvacMesh = new THREE.Mesh(hvacGeometry, hvacMaterial);
        
        // 风扇叶片
        for (let i = 0; i < 4; i++) {
          const bladeGeometry = new THREE.BoxGeometry(0.8, 0.1, 0.05);
          const bladeMaterial = new THREE.MeshLambertMaterial({ color: 0x888888 });
          const bladeMesh = new THREE.Mesh(bladeGeometry, bladeMaterial);
          bladeMesh.rotation.z = (i * Math.PI) / 2;
          bladeMesh.position.y = 0.25;
          iconGroup.add(bladeMesh);
        }
        
        iconGroup.add(hvacMesh);
        break;
        
      case 'security':
        // 安防图标 - 摄像头形状
        const cameraGeometry = new THREE.BoxGeometry(0.4, 0.4, 0.8);
        const cameraMaterial = new THREE.MeshLambertMaterial({ 
          color: device.status === 'online' ? 0x9C27B0 : 
                 device.status === 'maintenance' ? 0xFF9800 : 0xF44336
        });
        const cameraMesh = new THREE.Mesh(cameraGeometry, cameraMaterial);
        
        // 镜头
        const lensGeometry = new THREE.CylinderGeometry(0.15, 0.15, 0.3, 8);
        const lensMaterial = new THREE.MeshLambertMaterial({ color: 0x333333 });
        const lensMesh = new THREE.Mesh(lensGeometry, lensMaterial);
        lensMesh.rotation.x = Math.PI / 2;
        lensMesh.position.z = 0.55;
        
        iconGroup.add(cameraMesh);
        iconGroup.add(lensMesh);
        break;
        
      case 'lighting':
        // 照明图标 - 灯泡形状
        const bulbGeometry = new THREE.SphereGeometry(0.4, 8, 6);
        const bulbMaterial = new THREE.MeshLambertMaterial({ 
          color: device.status === 'online' ? 0xFFEB3B : 
                 device.status === 'maintenance' ? 0xFF9800 : 0xF44336,
          emissive: device.status === 'online' ? 0x444400 : 0x000000,
          emissiveIntensity: device.status === 'online' ? 0.3 : 0
        });
        const bulbMesh = new THREE.Mesh(bulbGeometry, bulbMaterial);
        
        // 灯座
        const baseGeometry = new THREE.CylinderGeometry(0.2, 0.3, 0.4, 8);
        const baseMaterial = new THREE.MeshLambertMaterial({ color: 0x666666 });
        const baseMesh = new THREE.Mesh(baseGeometry, baseMaterial);
        baseMesh.position.y = -0.6;
        
        iconGroup.add(bulbMesh);
        iconGroup.add(baseMesh);
        break;
        
      case 'fire_safety':
        // 消防图标 - 警报器形状
        const alarmGeometry = new THREE.ConeGeometry(0.5, 0.8, 8);
        const alarmMaterial = new THREE.MeshLambertMaterial({ 
          color: device.status === 'online' ? 0xFF5722 : 
                 device.status === 'maintenance' ? 0xFF9800 : 0xF44336
        });
        const alarmMesh = new THREE.Mesh(alarmGeometry, alarmMaterial);
        
        // 警报灯
        const lightGeometry = new THREE.SphereGeometry(0.15, 8, 6);
        const lightMaterial = new THREE.MeshLambertMaterial({ 
          color: 0xFF0000,
          emissive: device.status === 'online' ? 0x440000 : 0x000000,
          emissiveIntensity: device.status === 'online' ? 0.5 : 0
        });
        const lightMesh = new THREE.Mesh(lightGeometry, lightMaterial);
        lightMesh.position.y = 0.5;
        
        iconGroup.add(alarmMesh);
        iconGroup.add(lightMesh);
        break;
        
      case 'access_control':
        // 门禁图标 - 门形状
        const doorFrameGeometry = new THREE.BoxGeometry(0.8, 1.2, 0.1);
        const doorFrameMaterial = new THREE.MeshLambertMaterial({ 
          color: device.status === 'online' ? 0x607D8B : 
                 device.status === 'maintenance' ? 0xFF9800 : 0xF44336
        });
        const doorFrameMesh = new THREE.Mesh(doorFrameGeometry, doorFrameMaterial);
        
        // 门把手
        const handleGeometry = new THREE.SphereGeometry(0.08, 6, 4);
        const handleMaterial = new THREE.MeshLambertMaterial({ color: 0xFFD700 });
        const handleMesh = new THREE.Mesh(handleGeometry, handleMaterial);
        handleMesh.position.set(0.3, 0, 0.1);
        
        iconGroup.add(doorFrameMesh);
        iconGroup.add(handleMesh);
        break;
        
      default:
        // 默认设备图标 - 简单立方体
        const defaultGeometry = new THREE.BoxGeometry(0.6, 0.6, 0.6);
        const defaultMaterial = new THREE.MeshLambertMaterial({ 
          color: device.status === 'online' ? 0x9E9E9E : 
                 device.status === 'maintenance' ? 0xFF9800 : 0xF44336
        });
        const defaultMesh = new THREE.Mesh(defaultGeometry, defaultMaterial);
        iconGroup.add(defaultMesh);
        break;
    }
    
    // 添加状态指示环
    const ringGeometry = new THREE.RingGeometry(0.8, 1.0, 16);
    const ringMaterial = new THREE.MeshLambertMaterial({ 
      color: device.status === 'online' ? 0x00FF00 : 
             device.status === 'maintenance' ? 0xFFFF00 : 
             device.status === 'offline' ? 0x666666 : 0xFF0000,
      side: THREE.DoubleSide,
      transparent: true,
      opacity: 0.6
    });
    const ringMesh = new THREE.Mesh(ringGeometry, ringMaterial);
    ringMesh.rotation.x = -Math.PI / 2;
    ringMesh.position.y = -0.8;
    iconGroup.add(ringMesh);
    
    return iconGroup;
  }, []);

  // 创建电梯3D模型
  const createElevator = useCallback((elevator: ElevatorData, buildingHeight: number): THREE.Group => {
    const elevatorGroup = new THREE.Group();
    
    // 电梯井道
    const shaftGeometry = new THREE.BoxGeometry(1.5, buildingHeight, 1.5);
    const shaftMaterial = new THREE.MeshLambertMaterial({ 
      color: 0x333333,
      transparent: true,
      opacity: 0.7
    });
    const shaftMesh = new THREE.Mesh(shaftGeometry, shaftMaterial);
    shaftMesh.position.y = buildingHeight / 2;
    
    // 状态指示灯
    const indicatorGeometry = new THREE.SphereGeometry(0.15, 8, 8);
    const indicatorMaterial = new THREE.MeshLambertMaterial({ 
      color: getElevatorColor(elevator),
      emissive: getElevatorColor(elevator),
      emissiveIntensity: 0.4
    });
    const indicatorMesh = new THREE.Mesh(indicatorGeometry, indicatorMaterial);
    indicatorMesh.position.set(0, buildingHeight + 1.5, 0);
    
    elevatorGroup.add(shaftMesh);
    elevatorGroup.add(indicatorMesh);
    
    // 设置用户数据
    elevatorGroup.userData = { elevator, building: null };
    
    return elevatorGroup;
  }, [getElevatorColor]);

  // 初始化3D场景
  const initScene = useCallback(() => {
    if (!mountRef.current) return;

    const currentMount = mountRef.current;
    
    // 创建场景
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0x000011);
    sceneRef.current = scene;

    // 创建相机
    const camera = new THREE.PerspectiveCamera(
      75,
      currentMount.clientWidth / currentMount.clientHeight,
      0.1,
      1000
    );
    camera.position.set(50, 50, 50);
    cameraRef.current = camera;

    // 创建渲染器（优化像素比与阴影类型）
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
    renderer.setSize(currentMount.clientWidth, currentMount.clientHeight);
    renderer.shadowMap.enabled = true;
    renderer.shadowMap.type = THREE.PCFSoftShadowMap;
    rendererRef.current = renderer;



    // 添加光源
    const ambientLight = new THREE.AmbientLight(0x404040, 0.6);
    scene.add(ambientLight);

    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
    directionalLight.position.set(50, 50, 25);
    directionalLight.castShadow = true;
    // 降低阴影贴图尺寸以减少 GPU 占用
    directionalLight.shadow.mapSize.width = 1024;
    directionalLight.shadow.mapSize.height = 1024;
    scene.add(directionalLight);

    // 创建地面
    const groundGeometry = new THREE.PlaneGeometry(200, 200);
    const groundMaterial = new THREE.MeshLambertMaterial({ color: 0x2F4F4F });
    const ground = new THREE.Mesh(groundGeometry, groundMaterial);
    ground.rotation.x = -Math.PI / 2;
    ground.receiveShadow = true;
    scene.add(ground);

    // 创建网格
    const gridHelper = new THREE.GridHelper(200, 20, 0x444444, 0x444444);
    scene.add(gridHelper);

    // 创建马路系统
    const roadGroup = new THREE.Group();
    
    // 主干道材质
    const mainRoadMaterial = new THREE.MeshLambertMaterial({ 
      color: 0x333333,
      transparent: true,
      opacity: 0.9
    });
    
    // 支路材质
    const sideRoadMaterial = new THREE.MeshLambertMaterial({ 
      color: 0x444444,
      transparent: true,
      opacity: 0.8
    });
    
    // 人行道材质
    const sidewalkMaterial = new THREE.MeshLambertMaterial({ 
      color: 0x666666,
      transparent: true,
      opacity: 0.7
    });
    
    // 马路标线材质
    const roadLineMaterial = new THREE.MeshLambertMaterial({ 
      color: 0xFFFFFF,
      transparent: true,
      opacity: 0.9
    });
    
    // 创建主干道（东西向）
    const mainRoadEW1 = new THREE.PlaneGeometry(160, 10);
    const mainRoadEW1Mesh = new THREE.Mesh(mainRoadEW1, mainRoadMaterial);
    mainRoadEW1Mesh.rotation.x = -Math.PI / 2;
    mainRoadEW1Mesh.position.set(0, 0.01, -25);
    roadGroup.add(mainRoadEW1Mesh);
    
    const mainRoadEW2 = new THREE.PlaneGeometry(160, 10);
    const mainRoadEW2Mesh = new THREE.Mesh(mainRoadEW2, mainRoadMaterial);
    mainRoadEW2Mesh.rotation.x = -Math.PI / 2;
    mainRoadEW2Mesh.position.set(0, 0.01, 30);
    roadGroup.add(mainRoadEW2Mesh);
    
    // 创建支路连接各楼宇
    const sideRoads = [
      // 连接办公楼区域的支路
      { width: 6, length: 40, x: -45, z: -40 },
      { width: 6, length: 40, x: -15, z: -40 },
      { width: 6, length: 40, x: 15, z: -40 },
      
      // 连接住宅区域的支路
      { width: 6, length: 30, x: -30, z: 10 },
      { width: 6, length: 30, x: 30, z: 10 },
      
      // 连接后排住宅的支路
      { width: 6, length: 25, x: -15, z: 50 },
      { width: 6, length: 25, x: 15, z: 50 },
      { width: 6, length: 25, x: 45, z: 50 },
    ];
    
    sideRoads.forEach(road => {
      const sideRoadGeometry = new THREE.PlaneGeometry(road.width, road.length);
      const sideRoadMesh = new THREE.Mesh(sideRoadGeometry, sideRoadMaterial);
      sideRoadMesh.rotation.x = -Math.PI / 2;
      sideRoadMesh.position.set(road.x, 0.02, road.z);
      roadGroup.add(sideRoadMesh);
    });
    
    // 创建人行道
    const sidewalks = [
      // 东西向主干道的人行道
      { width: 160, length: 2, x: 0, z: -30 },
      { width: 160, length: 2, x: 0, z: -20 },
      { width: 160, length: 2, x: 0, z: 25 },
      { width: 160, length: 2, x: 0, z: 35 },
    ];
    
    sidewalks.forEach(sidewalk => {
      const sidewalkGeometry = new THREE.PlaneGeometry(sidewalk.width, sidewalk.length);
      const sidewalkMesh = new THREE.Mesh(sidewalkGeometry, sidewalkMaterial);
      sidewalkMesh.rotation.x = -Math.PI / 2;
      sidewalkMesh.position.set(sidewalk.x, 0.03, sidewalk.z);
      roadGroup.add(sidewalkMesh);
    });
    
    // 创建马路标线
    const roadLines = [
      // 东西向主干道中央线
      { width: 160, length: 0.3, x: 0, z: -25 },
      { width: 160, length: 0.3, x: 0, z: 30 },
    ];
    
    roadLines.forEach(line => {
      const lineGeometry = new THREE.PlaneGeometry(line.width, line.length);
      const lineMesh = new THREE.Mesh(lineGeometry, roadLineMaterial);
      lineMesh.rotation.x = -Math.PI / 2;
      lineMesh.position.set(line.x, 0.04, line.z);
      roadGroup.add(lineMesh);
    });
    
    // 创建斑马线
    const crosswalks = [
      { x: -20, z: -25 },
      { x: 20, z: -25 },
      { x: -20, z: 30 },
      { x: 20, z: 30 },
    ];
    
    crosswalks.forEach(crosswalk => {
      for (let i = 0; i < 8; i++) {
        const stripeGeometry = new THREE.PlaneGeometry(1.5, 0.8);
        const stripeMesh = new THREE.Mesh(stripeGeometry, roadLineMaterial);
        stripeMesh.rotation.x = -Math.PI / 2;
        stripeMesh.position.set(
          crosswalk.x + (i - 3.5) * 2,
          0.05,
          crosswalk.z
        );
        roadGroup.add(stripeMesh);
      }
    });
    
    // 创建交通标志和装饰
    const trafficSigns = [
      { x: -10, z: -10, type: 'stop' },
      { x: 10, z: 20, type: 'yield' },
      { x: -25, z: -25, type: 'speed' },
      { x: 25, z: 30, type: 'direction' },
    ];
    
    trafficSigns.forEach(sign => {
      // 标志杆
      const poleGeometry = new THREE.CylinderGeometry(0.1, 0.1, 3, 8);
      const poleMaterial = new THREE.MeshLambertMaterial({ color: 0x888888 });
      const poleMesh = new THREE.Mesh(poleGeometry, poleMaterial);
      poleMesh.position.set(sign.x, 1.5, sign.z);
      roadGroup.add(poleMesh);
      
      // 标志牌
      const signGeometry = new THREE.PlaneGeometry(1.5, 1.5);
      let signColor = 0xFF0000; // 默认红色
      switch (sign.type) {
        case 'stop': signColor = 0xFF0000; break;
        case 'yield': signColor = 0xFFFF00; break;
        case 'speed': signColor = 0x0000FF; break;
        case 'direction': signColor = 0x00FF00; break;
      }
      const signMaterial = new THREE.MeshLambertMaterial({ color: signColor });
      const signMesh = new THREE.Mesh(signGeometry, signMaterial);
      signMesh.position.set(sign.x, 2.8, sign.z);
      roadGroup.add(signMesh);
    });
    
    // 创建路边装饰
    const decorations = [
      // 绿化带
      { x: -12, z: 0, type: 'greenery' },
      { x: 12, z: 0, type: 'greenery' },
      
      // 垃圾桶
      { x: -8, z: -15, type: 'bin' },
      { x: 8, z: 15, type: 'bin' },
      
      // 公交站牌
      { x: -15, z: -30, type: 'bus_stop' },
      { x: 15, z: 35, type: 'bus_stop' },
    ];
    
    decorations.forEach(deco => {
      switch (deco.type) {
        case 'greenery':
          // 绿化带
          const greenGeometry = new THREE.PlaneGeometry(2, 20);
          const greenMaterial = new THREE.MeshLambertMaterial({ color: 0x228B22 });
          const greenMesh = new THREE.Mesh(greenGeometry, greenMaterial);
          greenMesh.rotation.x = -Math.PI / 2;
          greenMesh.position.set(deco.x, 0.06, deco.z);
          roadGroup.add(greenMesh);
          
          // 添加一些小树
          for (let i = 0; i < 3; i++) {
            const treeGeometry = new THREE.ConeGeometry(0.5, 2, 8);
            const treeMaterial = new THREE.MeshLambertMaterial({ color: 0x006400 });
            const treeMesh = new THREE.Mesh(treeGeometry, treeMaterial);
            treeMesh.position.set(deco.x, 1, deco.z + (i - 1) * 8);
            roadGroup.add(treeMesh);
          }
          break;
          
        case 'bin':
          // 垃圾桶
          const binGeometry = new THREE.CylinderGeometry(0.3, 0.3, 0.8, 8);
          const binMaterial = new THREE.MeshLambertMaterial({ color: 0x404040 });
          const binMesh = new THREE.Mesh(binGeometry, binMaterial);
          binMesh.position.set(deco.x, 0.4, deco.z);
          roadGroup.add(binMesh);
          break;
          
        case 'bus_stop':
          // 公交站牌
          const stopPoleGeometry = new THREE.CylinderGeometry(0.08, 0.08, 2.5, 8);
          const stopPoleMaterial = new THREE.MeshLambertMaterial({ color: 0x666666 });
          const stopPoleMesh = new THREE.Mesh(stopPoleGeometry, stopPoleMaterial);
          stopPoleMesh.position.set(deco.x, 1.25, deco.z);
          roadGroup.add(stopPoleMesh);
          
          const stopSignGeometry = new THREE.PlaneGeometry(2, 1);
          const stopSignMaterial = new THREE.MeshLambertMaterial({ color: 0x0066CC });
          const stopSignMesh = new THREE.Mesh(stopSignGeometry, stopSignMaterial);
          stopSignMesh.position.set(deco.x, 2.2, deco.z);
          roadGroup.add(stopSignMesh);
          break;
      }
    });
    
    scene.add(roadGroup);

    // 创建车辆系统
    const vehicleGroup = new THREE.Group();
    
    // 创建车辆函数
    const createVehicle = (type: 'car' | 'truck' | 'bus', color: number): THREE.Group => {
      const vehicle = new THREE.Group();
      
      switch (type) {
        case 'car':
          // 车身
          const carBodyGeometry = new THREE.BoxGeometry(4, 1.5, 2);
          const carBodyMaterial = new THREE.MeshLambertMaterial({ color });
          const carBodyMesh = new THREE.Mesh(carBodyGeometry, carBodyMaterial);
          carBodyMesh.position.y = 1;
          vehicle.add(carBodyMesh);
          
          // 车顶
          const carRoofGeometry = new THREE.BoxGeometry(3, 1, 1.8);
          const carRoofMaterial = new THREE.MeshLambertMaterial({ color: color * 0.8 });
          const carRoofMesh = new THREE.Mesh(carRoofGeometry, carRoofMaterial);
          carRoofMesh.position.y = 2;
          vehicle.add(carRoofMesh);
          
          // 车轮
          const wheelGeometry = new THREE.CylinderGeometry(0.4, 0.4, 0.3, 8);
          const wheelMaterial = new THREE.MeshLambertMaterial({ color: 0x333333 });
          
          const wheelPositions = [
            { x: -1.3, y: 0.4, z: 0.8 },
            { x: 1.3, y: 0.4, z: 0.8 },
            { x: -1.3, y: 0.4, z: -0.8 },
            { x: 1.3, y: 0.4, z: -0.8 }
          ];
          
          wheelPositions.forEach(pos => {
            const wheel = new THREE.Mesh(wheelGeometry, wheelMaterial);
            wheel.position.set(pos.x, pos.y, pos.z);
            wheel.rotation.z = Math.PI / 2;
            vehicle.add(wheel);
          });
          
          // 车灯
          const headlightGeometry = new THREE.SphereGeometry(0.2, 8, 6);
          const headlightMaterial = new THREE.MeshLambertMaterial({ 
            color: 0xFFFFFF,
            emissive: 0x444444,
            emissiveIntensity: 0.3
          });
          
          const leftHeadlight = new THREE.Mesh(headlightGeometry, headlightMaterial);
          leftHeadlight.position.set(-1.8, 1.2, 0.6);
          vehicle.add(leftHeadlight);
          
          const rightHeadlight = new THREE.Mesh(headlightGeometry, headlightMaterial);
          rightHeadlight.position.set(-1.8, 1.2, -0.6);
          vehicle.add(rightHeadlight);
          break;
          
        case 'truck':
          // 卡车驾驶室
          const truckCabGeometry = new THREE.BoxGeometry(2.5, 2, 2.2);
          const truckCabMaterial = new THREE.MeshLambertMaterial({ color });
          const truckCabMesh = new THREE.Mesh(truckCabGeometry, truckCabMaterial);
          truckCabMesh.position.set(-1.5, 1.2, 0);
          vehicle.add(truckCabMesh);
          
          // 卡车货箱
          const truckCargoGeometry = new THREE.BoxGeometry(4, 2.5, 2.2);
          const truckCargoMaterial = new THREE.MeshLambertMaterial({ color: color * 0.9 });
          const truckCargoMesh = new THREE.Mesh(truckCargoGeometry, truckCargoMaterial);
          truckCargoMesh.position.set(1.5, 1.5, 0);
          vehicle.add(truckCargoMesh);
          
          // 卡车车轮
          const truckWheelGeometry = new THREE.CylinderGeometry(0.5, 0.5, 0.4, 8);
          const truckWheelMaterial = new THREE.MeshLambertMaterial({ color: 0x333333 });
          
          const truckWheelPositions = [
            { x: -2.2, y: 0.5, z: 0.9 },
            { x: -2.2, y: 0.5, z: -0.9 },
            { x: 0.8, y: 0.5, z: 0.9 },
            { x: 0.8, y: 0.5, z: -0.9 },
            { x: 2.2, y: 0.5, z: 0.9 },
            { x: 2.2, y: 0.5, z: -0.9 }
          ];
          
          truckWheelPositions.forEach(pos => {
            const wheel = new THREE.Mesh(truckWheelGeometry, truckWheelMaterial);
            wheel.position.set(pos.x, pos.y, pos.z);
            wheel.rotation.z = Math.PI / 2;
            vehicle.add(wheel);
          });
          break;
          
        case 'bus':
          // 公交车车身
          const busBodyGeometry = new THREE.BoxGeometry(8, 2.5, 2.5);
          const busBodyMaterial = new THREE.MeshLambertMaterial({ color });
          const busBodyMesh = new THREE.Mesh(busBodyGeometry, busBodyMaterial);
          busBodyMesh.position.y = 1.5;
          vehicle.add(busBodyMesh);
          
          // 公交车窗户
          const windowGeometry = new THREE.PlaneGeometry(6, 1);
          const windowMaterial = new THREE.MeshLambertMaterial({ 
            color: 0x87CEEB,
            transparent: true,
            opacity: 0.7
          });
          
          const leftWindow = new THREE.Mesh(windowGeometry, windowMaterial);
          leftWindow.position.set(0, 2, 1.26);
          vehicle.add(leftWindow);
          
          const rightWindow = new THREE.Mesh(windowGeometry, windowMaterial);
          rightWindow.position.set(0, 2, -1.26);
          vehicle.add(rightWindow);
          
          // 公交车车轮
          const busWheelGeometry = new THREE.CylinderGeometry(0.6, 0.6, 0.4, 8);
          const busWheelMaterial = new THREE.MeshLambertMaterial({ color: 0x333333 });
          
          const busWheelPositions = [
            { x: -2.5, y: 0.6, z: 1 },
            { x: -2.5, y: 0.6, z: -1 },
            { x: 2.5, y: 0.6, z: 1 },
            { x: 2.5, y: 0.6, z: -1 }
          ];
          
          busWheelPositions.forEach(pos => {
            const wheel = new THREE.Mesh(busWheelGeometry, busWheelMaterial);
            wheel.position.set(pos.x, pos.y, pos.z);
            wheel.rotation.z = Math.PI / 2;
            vehicle.add(wheel);
          });
          
          // 公交车门
          const doorGeometry = new THREE.PlaneGeometry(0.8, 1.8);
          const doorMaterial = new THREE.MeshLambertMaterial({ color: 0x444444 });
          const door = new THREE.Mesh(doorGeometry, doorMaterial);
          door.position.set(1, 1.2, 1.26);
          vehicle.add(door);
          break;
      }
      
      return vehicle;
    };
    
    // 在东西向主干道上添加车辆
    const vehicles = [
      // 第一条东西向主干道上的车辆 (z = -25)
      { type: 'car' as const, color: 0xFF0000, x: -40, z: -25, rotation: 0 },
      { type: 'car' as const, color: 0x0000FF, x: -20, z: -25, rotation: 0 },
      { type: 'truck' as const, color: 0x00FF00, x: 0, z: -25, rotation: 0 },
      { type: 'car' as const, color: 0xFFFF00, x: 20, z: -25, rotation: 0 },
      { type: 'bus' as const, color: 0xFF8800, x: 40, z: -25, rotation: 0 },
      
      // 第二条东西向主干道上的车辆 (z = 30)
      { type: 'car' as const, color: 0x8800FF, x: -35, z: 30, rotation: Math.PI },
      { type: 'car' as const, color: 0x00FFFF, x: -15, z: 30, rotation: Math.PI },
      { type: 'truck' as const, color: 0xFF0088, x: 5, z: 30, rotation: Math.PI },
      { type: 'car' as const, color: 0x88FF00, x: 25, z: 30, rotation: Math.PI },
      { type: 'car' as const, color: 0xFF8888, x: 45, z: 30, rotation: Math.PI },
      
      // 支路上的车辆
      { type: 'car' as const, color: 0x4444FF, x: -45, z: -35, rotation: Math.PI / 2 },
      { type: 'car' as const, color: 0xFF4444, x: -15, z: -35, rotation: Math.PI / 2 },
      { type: 'car' as const, color: 0x44FF44, x: 15, z: -35, rotation: Math.PI / 2 },
      
      { type: 'car' as const, color: 0x8844FF, x: -30, z: 15, rotation: -Math.PI / 2 },
      { type: 'car' as const, color: 0xFF8844, x: 30, z: 15, rotation: -Math.PI / 2 },
      
      { type: 'car' as const, color: 0x4488FF, x: -15, z: 55, rotation: Math.PI / 2 },
      { type: 'car' as const, color: 0xFF4488, x: 15, z: 55, rotation: Math.PI / 2 },
      { type: 'car' as const, color: 0x88FF44, x: 45, z: 55, rotation: Math.PI / 2 },
    ];
    
    vehicles.forEach(vehicleData => {
      const vehicle = createVehicle(vehicleData.type, vehicleData.color);
      vehicle.position.set(vehicleData.x, 0.1, vehicleData.z);
      vehicle.rotation.y = vehicleData.rotation;
      vehicleGroup.add(vehicle);
    });
    
    scene.add(vehicleGroup);

    // 创建楼宇
    mockBuildingsDataPhase2.forEach((building) => {
      const buildingGroup = new THREE.Group();
      
      // 主楼体
      const buildingHeight = building.floors * 3;
      const geometry = new THREE.BoxGeometry(8, buildingHeight, 8);
      const material = new THREE.MeshLambertMaterial({ 
        color: getBuildingColor(building),
        transparent: true,
        opacity: 0.8
      });
      const buildingMesh = new THREE.Mesh(geometry, material);
      buildingMesh.position.y = buildingHeight / 2;
      buildingMesh.castShadow = true;
      buildingMesh.receiveShadow = true;
      
      // 楼宇边框
      const edges = new THREE.EdgesGeometry(geometry);
      const lineMaterial = new THREE.LineBasicMaterial({ 
        color: 0xffffff,
        linewidth: 2
      });
      const wireframe = new THREE.LineSegments(edges, lineMaterial);
      wireframe.position.y = buildingHeight / 2;
      
      buildingGroup.add(buildingMesh);
      buildingGroup.add(wireframe);

      // 添加窗户装饰
      const windowMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x87CEEB,
        transparent: true,
        opacity: 0.7
      });
      
      // 窗框材质
      const windowFrameMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x8B4513,
        transparent: true,
        opacity: 0.9
      });
      
      // 在楼宇四面添加窗户
      for (let floor = 1; floor < building.floors; floor += 2) {
        for (let side = 0; side < 4; side++) {
          for (let window = 0; window < 3; window++) {
            // 窗户玻璃
            const windowGeometry = new THREE.BoxGeometry(0.8, 1.2, 0.1);
            const windowMesh = new THREE.Mesh(windowGeometry, windowMaterial);
            
            // 窗框
            const frameGeometry = new THREE.BoxGeometry(1.0, 1.4, 0.15);
            const frameMesh = new THREE.Mesh(frameGeometry, windowFrameMaterial);
            
            const floorY = floor * 3;
            const windowX = (window - 1) * 2;
            
            if (side === 0) { // 前面
              windowMesh.position.set(windowX, floorY, 4.1);
              frameMesh.position.set(windowX, floorY, 4.05);
            } else if (side === 1) { // 右面
              windowMesh.position.set(4.1, floorY, windowX);
              frameMesh.position.set(4.05, floorY, windowX);
            } else if (side === 2) { // 后面
              windowMesh.position.set(windowX, floorY, -4.1);
              frameMesh.position.set(windowX, floorY, -4.05);
            } else { // 左面
              windowMesh.position.set(-4.1, floorY, windowX);
              frameMesh.position.set(-4.05, floorY, windowX);
            }
            
            // 添加窗户反光效果（随机）
            if (Math.random() > 0.7) {
              const reflectionMaterial = new THREE.MeshLambertMaterial({ 
                color: 0xFFFFFF,
                transparent: true,
                opacity: 0.3,
                emissive: 0xFFFFFF,
                emissiveIntensity: 0.1
              });
              const reflectionMesh = new THREE.Mesh(windowGeometry, reflectionMaterial);
              reflectionMesh.position.copy(windowMesh.position);
              reflectionMesh.position.z += side === 0 ? 0.01 : side === 2 ? -0.01 : 0;
              reflectionMesh.position.x += side === 1 ? 0.01 : side === 3 ? -0.01 : 0;
              buildingGroup.add(reflectionMesh);
            }
            
            buildingGroup.add(windowMesh);
            buildingGroup.add(frameMesh);
          }
        }
      }
      
      // 添加阳台装饰（住宅楼）
      if (building.type === 'residential') {
        for (let floor = 3; floor < building.floors; floor += 5) {
          const balconyGeometry = new THREE.BoxGeometry(9, 0.2, 1.5);
          const balconyMaterial = new THREE.MeshLambertMaterial({ color: 0x8B4513 });
          const balconyMesh = new THREE.Mesh(balconyGeometry, balconyMaterial);
          balconyMesh.position.set(0, floor * 3, 5);
          buildingGroup.add(balconyMesh);
        }
      }
      
      // 楼宇顶部标识和天线
      const topGeometry = new THREE.CylinderGeometry(1, 1, 2, 8);
      const topMaterial = new THREE.MeshLambertMaterial({ 
        color: getBuildingTypeColor(building.type) 
      });
      const topMesh = new THREE.Mesh(topGeometry, topMaterial);
      topMesh.position.y = buildingHeight + 1;
      
      // 添加天线
      const antennaGeometry = new THREE.CylinderGeometry(0.1, 0.1, 8, 8);
      const antennaMaterial = new THREE.MeshLambertMaterial({ color: 0x666666 });
      const antennaMesh = new THREE.Mesh(antennaGeometry, antennaMaterial);
      antennaMesh.position.y = buildingHeight + 6;
      
      // 天线顶部信号灯
      const signalGeometry = new THREE.SphereGeometry(0.3, 8, 8);
      const signalMaterial = new THREE.MeshLambertMaterial({ 
        color: building.status === 'normal' ? 0x00FF00 : 
               building.status === 'medium' ? 0xFFFF00 : 0xFF0000,
        emissive: building.status === 'normal' ? 0x004400 : 
                  building.status === 'medium' ? 0x444400 : 0x440000
      });
      const signalMesh = new THREE.Mesh(signalGeometry, signalMaterial);
      signalMesh.position.y = buildingHeight + 10;
      
      // 地基
      const baseGeometry = new THREE.CylinderGeometry(6, 6, 1, 16);
      const baseMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x424242,
        transparent: true,
        opacity: 0.6
      });
      const baseMesh = new THREE.Mesh(baseGeometry, baseMaterial);
      baseMesh.position.y = 0.5;
      
      // 地基装饰环
      const ringGeometry = new THREE.RingGeometry(6, 7, 16);
      const ringMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x666666,
        side: THREE.DoubleSide
      });
      const ringMesh = new THREE.Mesh(ringGeometry, ringMaterial);
      ringMesh.rotation.x = -Math.PI / 2;
      ringMesh.position.y = 1;
      
      // 添加楼宇入口装饰
      const entranceGeometry = new THREE.BoxGeometry(3, 4, 1);
      const entranceMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x8B4513,
        transparent: true,
        opacity: 0.8
      });
      const entranceMesh = new THREE.Mesh(entranceGeometry, entranceMaterial);
      entranceMesh.position.set(0, 2, 4.5);
      
      // 入口玻璃门
      const doorGlassGeometry = new THREE.PlaneGeometry(2.5, 3.5);
      const doorGlassMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x87CEEB,
        transparent: true,
        opacity: 0.3
      });
      const doorGlassMesh = new THREE.Mesh(doorGlassGeometry, doorGlassMaterial);
      doorGlassMesh.position.set(0, 2, 5.1);
      
      // 楼宇标识牌
      const signGeometry = new THREE.PlaneGeometry(4, 1);
      const signMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x2F4F4F,
        side: THREE.DoubleSide
      });
      const signMesh = new THREE.Mesh(signGeometry, signMaterial);
      signMesh.position.set(0, 6, 4.5);
      
      // 屋顶装饰
      const roofDecoGeometry = new THREE.ConeGeometry(2, 3, 8);
      const roofDecoMaterial = new THREE.MeshLambertMaterial({ 
        color: getBuildingTypeColor(building.type),
        emissive: getBuildingTypeColor(building.type),
        emissiveIntensity: 0.1
      });
      const roofDecoMesh = new THREE.Mesh(roofDecoGeometry, roofDecoMaterial);
      roofDecoMesh.position.y = buildingHeight + 4;

      buildingGroup.add(topMesh);
      buildingGroup.add(antennaMesh);
      buildingGroup.add(signalMesh);
      buildingGroup.add(baseMesh);
      buildingGroup.add(ringMesh);
      buildingGroup.add(entranceMesh);
      buildingGroup.add(doorGlassMesh);
      buildingGroup.add(signMesh);
      buildingGroup.add(roofDecoMesh);
      
      // 添加空调外机装饰
      for (let floor = 2; floor < building.floors; floor += 3) {
        for (let side = 0; side < 4; side++) {
          if (Math.random() > 0.6) { // 随机分布空调外机
            const acGeometry = new THREE.BoxGeometry(0.8, 0.6, 0.4);
            const acMaterial = new THREE.MeshLambertMaterial({ color: 0xC0C0C0 });
            const acMesh = new THREE.Mesh(acGeometry, acMaterial);
            
            const acY = floor * 3 - 1;
            const acOffset = (Math.random() - 0.5) * 4;
            
            if (side === 0) { // 前面
              acMesh.position.set(acOffset, acY, 4.5);
            } else if (side === 1) { // 右面
              acMesh.position.set(4.5, acY, acOffset);
            } else if (side === 2) { // 后面
              acMesh.position.set(acOffset, acY, -4.5);
            } else { // 左面
              acMesh.position.set(-4.5, acY, acOffset);
            }
            
            // 空调外机风扇
            const fanGeometry = new THREE.CylinderGeometry(0.2, 0.2, 0.1, 8);
            const fanMaterial = new THREE.MeshLambertMaterial({ color: 0x333333 });
            const fanMesh = new THREE.Mesh(fanGeometry, fanMaterial);
            fanMesh.position.copy(acMesh.position);
            fanMesh.position.y += 0.35;
            fanMesh.rotation.x = Math.PI / 2;
            
            buildingGroup.add(acMesh);
            buildingGroup.add(fanMesh);
          }
        }
      }
      
      // 添加广告牌装饰（商业建筑）
      if (building.type === 'commercial') {
        const billboardGeometry = new THREE.PlaneGeometry(6, 3);
        const billboardMaterial = new THREE.MeshLambertMaterial({ 
          color: 0xFF6B6B,
          transparent: true,
          opacity: 0.9
        });
        const billboardMesh = new THREE.Mesh(billboardGeometry, billboardMaterial);
        billboardMesh.position.set(0, buildingHeight - 5, 4.2);
        
        // 广告牌边框
        const billboardFrameGeometry = new THREE.PlaneGeometry(6.2, 3.2);
        const billboardFrameMaterial = new THREE.MeshLambertMaterial({ 
          color: 0x333333,
          side: THREE.DoubleSide
        });
        const billboardFrameMesh = new THREE.Mesh(billboardFrameGeometry, billboardFrameMaterial);
        billboardFrameMesh.position.set(0, buildingHeight - 5, 4.15);
        
        // 广告牌灯光
        const lightGeometry = new THREE.SphereGeometry(0.1, 8, 8);
        const lightMaterial = new THREE.MeshLambertMaterial({ 
          color: 0xFFFFFF,
          emissive: 0xFFFFFF,
          emissiveIntensity: 0.3
        });
        
        for (let i = 0; i < 4; i++) {
          const lightMesh = new THREE.Mesh(lightGeometry, lightMaterial);
          lightMesh.position.set((i - 1.5) * 2, buildingHeight - 3.5, 4.3);
          buildingGroup.add(lightMesh);
        }
        
        buildingGroup.add(billboardFrameMesh);
        buildingGroup.add(billboardMesh);
      }
      
      // 添加卫星天线（办公楼）
      if (building.type === 'office') {
        const dishGeometry = new THREE.SphereGeometry(1.5, 16, 8, 0, Math.PI * 2, 0, Math.PI / 2);
        const dishMaterial = new THREE.MeshLambertMaterial({ color: 0xE0E0E0 });
        const dishMesh = new THREE.Mesh(dishGeometry, dishMaterial);
        dishMesh.position.set(2, buildingHeight + 2, 2);
        dishMesh.rotation.x = -Math.PI / 4;
        
        // 天线支架
        const supportGeometry = new THREE.CylinderGeometry(0.1, 0.1, 3, 8);
        const supportMaterial = new THREE.MeshLambertMaterial({ color: 0x666666 });
        const supportMesh = new THREE.Mesh(supportGeometry, supportMaterial);
        supportMesh.position.set(2, buildingHeight + 0.5, 2);
        
        buildingGroup.add(dishMesh);
        buildingGroup.add(supportMesh);
      }
      
      // 添加太阳能板（绿色建筑）
      if (building.type === 'mixed' || Math.random() > 0.7) {
        for (let i = 0; i < 3; i++) {
          const solarGeometry = new THREE.PlaneGeometry(2, 1);
          const solarMaterial = new THREE.MeshLambertMaterial({ 
            color: 0x1E3A8A,
            transparent: true,
            opacity: 0.8
          });
          const solarMesh = new THREE.Mesh(solarGeometry, solarMaterial);
          solarMesh.position.set((i - 1) * 2.5, buildingHeight + 0.1, 0);
          solarMesh.rotation.x = -Math.PI / 2;
          solarMesh.rotation.z = Math.PI / 8;
          
          // 太阳能板框架
          const frameGeometry = new THREE.PlaneGeometry(2.1, 1.1);
          const frameMaterial = new THREE.MeshLambertMaterial({ 
            color: 0x333333,
            side: THREE.DoubleSide
          });
          const frameMesh = new THREE.Mesh(frameGeometry, frameMaterial);
          frameMesh.position.copy(solarMesh.position);
          frameMesh.position.y -= 0.01;
          frameMesh.rotation.copy(solarMesh.rotation);
          
          buildingGroup.add(frameMesh);
          buildingGroup.add(solarMesh);
        }
      }
      
      // 添加电梯
      building.elevators.forEach((elevator: ElevatorData, index: number) => {
        const elevatorGroup = createElevator(elevator, buildingHeight);
        const elevatorX = (index - building.elevators.length / 2) * 2;
        const elevatorZ = 5;
        elevatorGroup.position.set(elevatorX, 0, elevatorZ);
        elevatorGroup.userData.building = building;
        
        // 设置电梯用户数据用于点击检测
        elevatorGroup.userData = { 
          type: 'elevator',
          elevator: elevator,
          building: building,
          deviceInfo: mockDevicesDataPhase2.find(device => 
            device.name.includes(elevator.id) || 
            device.id.includes(elevator.id.replace(/[^0-9]/g, ''))
          )
        };
        buildingGroup.add(elevatorGroup);
      });

      // 为建筑物中的设备添加信息标签
      const buildingDevices = mockDevicesDataPhase2.filter(device => device.buildingId === building.id);
      buildingDevices.forEach((device, index) => {
        // 设备位置（在建筑物周围分布）
        const deviceAngle = (index / buildingDevices.length) * Math.PI * 2;
        const deviceDistance = 6;
        const deviceX = Math.cos(deviceAngle) * deviceDistance;
        const deviceZ = Math.sin(deviceAngle) * deviceDistance;
        const deviceY = Math.random() * buildingHeight * 0.8 + 2;

        // 创建设备指示器
         const deviceGeometry = new THREE.SphereGeometry(0.3, 8, 6);
         const deviceMaterial = new THREE.MeshLambertMaterial({ 
           color: device.status === 'online' ? 0x00FF00 : 
                  device.status === 'maintenance' ? 0xFFFF00 : 0xFF0000,
           emissive: device.status === 'online' ? 0x004400 : 
                     device.status === 'maintenance' ? 0x444400 : 0x440000
         });
        const deviceMesh = new THREE.Mesh(deviceGeometry, deviceMaterial);
        deviceMesh.position.set(deviceX, deviceY, deviceZ);
        
        // 设备连接线
        const lineGeometry = new THREE.BufferGeometry().setFromPoints([
          new THREE.Vector3(0, buildingHeight / 2, 0),
          new THREE.Vector3(deviceX, deviceY, deviceZ)
        ]);
        const lineMaterial = new THREE.LineBasicMaterial({ 
          color: 0x666666,
          transparent: true,
          opacity: 0.5
        });
        const deviceLine = new THREE.Line(lineGeometry, lineMaterial);
        
        // 创建3D设备图标
        const deviceIcon = createDeviceIcon(device);
        deviceIcon.position.set(deviceX, deviceY, deviceZ);
        
        // 设置设备用户数据用于点击检测
        deviceMesh.userData = {
          type: 'device',
          device: device,
          building: building
        };
        deviceIcon.userData = {
          type: 'device',
          device: device,
          building: building
        };
        
        buildingGroup.add(deviceMesh);
        buildingGroup.add(deviceLine);
        buildingGroup.add(deviceIcon);
      });
      
      // 添加楼宇周围绿化装饰
      const landscapeGroup = new THREE.Group();
      
      // 添加树木
      for (let i = 0; i < 4; i++) {
        const treeAngle = (i / 4) * Math.PI * 2;
        const treeDistance = 12 + Math.random() * 5;
        const treeX = Math.cos(treeAngle) * treeDistance;
        const treeZ = Math.sin(treeAngle) * treeDistance;
        
        // 树干
        const trunkGeometry = new THREE.CylinderGeometry(0.3, 0.5, 4, 8);
        const trunkMaterial = new THREE.MeshLambertMaterial({ color: 0x8B4513 });
        const trunkMesh = new THREE.Mesh(trunkGeometry, trunkMaterial);
        trunkMesh.position.set(treeX, 2, treeZ);
        
        // 树冠
        const crownGeometry = new THREE.SphereGeometry(2.5, 8, 6);
        const crownMaterial = new THREE.MeshLambertMaterial({ color: 0x228B22 });
        const crownMesh = new THREE.Mesh(crownGeometry, crownMaterial);
        crownMesh.position.set(treeX, 6, treeZ);
        
        landscapeGroup.add(trunkMesh);
        landscapeGroup.add(crownMesh);
      }
      
      // 添加花坛
      for (let i = 0; i < 6; i++) {
        const flowerAngle = (i / 6) * Math.PI * 2;
        const flowerDistance = 10;
        const flowerX = Math.cos(flowerAngle) * flowerDistance;
        const flowerZ = Math.sin(flowerAngle) * flowerDistance;
        
        // 花坛底座
        const bedGeometry = new THREE.CylinderGeometry(1.5, 1.5, 0.5, 8);
        const bedMaterial = new THREE.MeshLambertMaterial({ color: 0x8B4513 });
        const bedMesh = new THREE.Mesh(bedGeometry, bedMaterial);
        bedMesh.position.set(flowerX, 0.25, flowerZ);
        
        // 花朵
        for (let j = 0; j < 5; j++) {
          const flowerGeometry = new THREE.SphereGeometry(0.2, 6, 4);
          const flowerColors = [0xFF69B4, 0xFF1493, 0xFFB6C1, 0xFF6347, 0xFFA500];
          const flowerMaterial = new THREE.MeshLambertMaterial({ 
            color: flowerColors[j % flowerColors.length] 
          });
          const flowerMesh = new THREE.Mesh(flowerGeometry, flowerMaterial);
          const flowerLocalAngle = (j / 5) * Math.PI * 2;
          const flowerLocalX = Math.cos(flowerLocalAngle) * 0.8;
          const flowerLocalZ = Math.sin(flowerLocalAngle) * 0.8;
          flowerMesh.position.set(
            flowerX + flowerLocalX, 
            0.8, 
            flowerZ + flowerLocalZ
          );
          landscapeGroup.add(flowerMesh);
        }
        
        landscapeGroup.add(bedMesh);
      }
      
      // 添加路灯
      for (let i = 0; i < 8; i++) {
        const lampAngle = (i / 8) * Math.PI * 2;
        const lampDistance = 15;
        const lampX = Math.cos(lampAngle) * lampDistance;
        const lampZ = Math.sin(lampAngle) * lampDistance;
        
        // 路灯杆
        const poleGeometry = new THREE.CylinderGeometry(0.1, 0.15, 6, 8);
        const poleMaterial = new THREE.MeshLambertMaterial({ color: 0x333333 });
        const poleMesh = new THREE.Mesh(poleGeometry, poleMaterial);
        poleMesh.position.set(lampX, 3, lampZ);
        
        // 路灯头
        const lampGeometry = new THREE.SphereGeometry(0.5, 8, 6);
        const lampMaterial = new THREE.MeshLambertMaterial({ 
          color: 0xFFFFE0,
          emissive: 0xFFFFE0,
          emissiveIntensity: 0.2
        });
        const lampMesh = new THREE.Mesh(lampGeometry, lampMaterial);
        lampMesh.position.set(lampX, 6.5, lampZ);
        
        landscapeGroup.add(poleMesh);
        landscapeGroup.add(lampMesh);
      }
      
      // 添加小径
      const pathGeometry = new THREE.PlaneGeometry(2, 20);
      const pathMaterial = new THREE.MeshLambertMaterial({ 
        color: 0x696969,
        transparent: true,
        opacity: 0.8
      });
      const pathMesh = new THREE.Mesh(pathGeometry, pathMaterial);
      pathMesh.rotation.x = -Math.PI / 2;
      pathMesh.position.y = 0.01;
      landscapeGroup.add(pathMesh);
      
      // 添加装饰石块
      for (let i = 0; i < 10; i++) {
        const stoneGeometry = new THREE.DodecahedronGeometry(0.3 + Math.random() * 0.3);
        const stoneMaterial = new THREE.MeshLambertMaterial({ color: 0x708090 });
        const stoneMesh = new THREE.Mesh(stoneGeometry, stoneMaterial);
        const stoneAngle = Math.random() * Math.PI * 2;
        const stoneDistance = 8 + Math.random() * 10;
        stoneMesh.position.set(
          Math.cos(stoneAngle) * stoneDistance,
          0.3,
          Math.sin(stoneAngle) * stoneDistance
        );
        landscapeGroup.add(stoneMesh);
      }
      
      buildingGroup.add(landscapeGroup);
      
      // 设置楼宇位置
      buildingGroup.position.set(building.position.x, building.position.y, building.position.z);
      
      // 设置楼宇用户数据用于点击检测
      buildingGroup.userData = {
        type: 'building',
        building: building
      };
      
      scene.add(buildingGroup);
    });

    // 将渲染器添加到DOM
    currentMount.appendChild(renderer.domElement);

    // 设置轨道控制器
    const controls = new OrbitControls(camera, renderer.domElement);
    controls.enableDamping = true;
    controls.dampingFactor = 0.05;
    controls.screenSpacePanning = false;
    controls.minDistance = 10;
    controls.maxDistance = 200;
    controls.maxPolarAngle = Math.PI / 2;
    controlsRef.current = controls;

    // 点击检测
    const raycaster = new THREE.Raycaster();
    const mouse = new THREE.Vector2();

    const onMouseClick = (event: MouseEvent) => {
      const rect = renderer.domElement.getBoundingClientRect();
      mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
      mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;

      raycaster.setFromCamera(mouse, camera);
      const intersects = raycaster.intersectObjects(scene.children, true);

      if (intersects.length > 0) {
        let targetObject = intersects[0].object;
        
        // 向上查找包含用户数据的父对象
        while (targetObject && !targetObject.userData?.type) {
          targetObject = targetObject.parent as THREE.Object3D;
        }

        if (targetObject?.userData) {
          const userData = targetObject.userData;
          
          if (userData.type === 'device') {
            setSelectedDevice(userData.device);
            setDeviceModalVisible(true);
          } else if (userData.type === 'elevator') {
            // 查找对应的设备信息
            const elevatorDevice = userData.deviceInfo || mockDevicesDataPhase2.find(device => 
              device.name.includes(userData.elevator.id) || 
              device.id.includes(userData.elevator.id.replace(/[^0-9]/g, ''))
            );
            if (elevatorDevice) {
              setSelectedDevice(elevatorDevice);
              setDeviceModalVisible(true);
            }
          } else if (userData.type === 'building') {
            setSelectedBuilding(userData.building);
            setBuildingModalVisible(true);
          }
        }
      }
    };

    renderer.domElement.addEventListener('click', onMouseClick);

    // 动画循环（可见性感知，安全启动）
    const startLoop = () => {
      const animate = () => {
        if (document.hidden) {
          animationIdRef.current = undefined;
          return;
        }
        animationIdRef.current = requestAnimationFrame(animate);
        controls.update();
        renderer.render(scene, camera);
      };
      animate();
    };
    startLoopRef.current = startLoop;
    startLoop();

    // 页面可见性变化时控制动画循环
    const onVisibilityChange = () => {
      if (!document.hidden && !animationIdRef.current && startLoopRef.current) {
        startLoopRef.current();
      } else if (document.hidden && animationIdRef.current) {
        cancelAnimationFrame(animationIdRef.current);
        animationIdRef.current = undefined;
      }
    };
    document.addEventListener('visibilitychange', onVisibilityChange);

    // 窗口大小变化处理
    const handleResize = () => {
      if (currentMount) {
        camera.aspect = currentMount.clientWidth / currentMount.clientHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(currentMount.clientWidth, currentMount.clientHeight);
      }
    };

    window.addEventListener('resize', handleResize);

    // 清理函数
    return () => {
      if (animationIdRef.current) {
        cancelAnimationFrame(animationIdRef.current);
        animationIdRef.current = undefined;
      }
      document.removeEventListener('visibilitychange', onVisibilityChange);
      window.removeEventListener('resize', handleResize);
      renderer.domElement.removeEventListener('click', onMouseClick);
      if (controlsRef.current) {
        controlsRef.current.dispose();
        controlsRef.current = null;
      }
      if (sceneRef.current) {
        const clearScene = (object: THREE.Object3D) => {
          while (object.children.length > 0) {
            const child = object.children[0];
            clearScene(child);
            object.remove(child);
            if ((child as any).geometry && typeof (child as any).geometry.dispose === 'function') {
              (child as any).geometry.dispose();
            }
            const materialAny = (child as any).material;
            if (materialAny) {
              const disposeMaterial = (material: any) => {
                try {
                  const textureKeys = [
                    'map','lightMap','aoMap','emissiveMap','bumpMap','normalMap',
                    'displacementMap','roughnessMap','metalnessMap','alphaMap','envMap','gradientMap'
                  ];
                  textureKeys.forEach((key) => {
                    const tex = material && material[key];
                    if (tex && tex instanceof THREE.Texture) {
                      tex.dispose();
                    }
                  });
                } catch {}
                material.dispose && material.dispose();
              };
              if (Array.isArray(materialAny)) {
                materialAny.forEach(disposeMaterial);
              } else {
                disposeMaterial(materialAny);
              }
            }
          }
        };
        clearScene(sceneRef.current);
        sceneRef.current = null;
      }
      if (currentMount && renderer.domElement && currentMount.contains(renderer.domElement)) {
        try {
          currentMount.removeChild(renderer.domElement);
        } catch (error) {
          console.warn('Failed to remove renderer element:', error);
        }
      }
      renderer.dispose();
    };
  }, [getBuildingColor, getBuildingTypeColor, createDeviceIcon, createElevator]);

  // 组件挂载时初始化场景
  useEffect(() => {
    if (mountRef.current) {
      const cleanup = initScene();
      setIsLoading(false);
      return cleanup;
    }
  }, [initScene]);

  // 渲染设备信息表格
  const renderDeviceTable = (devices: DeviceData[]) => {
    const columns = [
      {
        title: '设备名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        render: (type: string) => {
          const typeMap: { [key: string]: string } = {
            elevator: '电梯',
            hvac: '空调',
            security: '安防',
            lighting: '照明',
            fire_safety: '消防',
            access_control: '门禁'
          };
          return typeMap[type] || type;
        }
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        render: (status: string) => {
          const statusConfig = {
            online: { color: 'green', text: '在线' },
            offline: { color: 'red', text: '离线' },
            maintenance: { color: 'orange', text: '维护中' },
            error: { color: 'red', text: '故障' }
          };
          const config = statusConfig[status as keyof typeof statusConfig] || { color: 'default', text: status };
          return <Tag color={config.color}>{config.text}</Tag>;
        }
      },
      {
        title: '位置',
        dataIndex: 'location',
        key: 'location',
      }
    ];

    return (
      <Table
        dataSource={devices}
        columns={columns}
        rowKey="id"
        size="small"
        pagination={false}
      />
    );
  };

  return (
    <div style={{ width: '100%', height: '100vh', position: 'relative' }}>
      {isLoading && (
        <div style={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          zIndex: 1000
        }}>
          <Spin size="large" />
        </div>
      )}
      <div ref={mountRef} style={{ width: '100%', height: '100%' }} />
      
      {/* 设备详细信息模态框 */}
      <Modal
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <DatabaseOutlined />
            设备详细信息
          </div>
        }
        open={deviceModalVisible}
        onCancel={() => setDeviceModalVisible(false)}
        footer={null}
        width={800}
      >
        {selectedDevice && (
          <div>
            <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
              <Col span={8}>
                <Statistic
                  title="设备状态"
                  value={selectedDevice.status === 'online' ? '在线' : 
                         selectedDevice.status === 'maintenance' ? '维护中' : 
                         selectedDevice.status === 'offline' ? '离线' : '故障'}
                  valueStyle={{ 
                    color: selectedDevice.status === 'online' ? '#3f8600' : 
                           selectedDevice.status === 'maintenance' ? '#cf1322' : '#cf1322'
                  }}
                  prefix={selectedDevice.status === 'online' ? <CheckCircleOutlined /> : 
                          selectedDevice.status === 'maintenance' ? <WarningOutlined /> : 
                          <ExclamationCircleOutlined />}
                />
              </Col>
              {selectedDevice.energyConsumption && (
                <Col span={8}>
                  <Statistic
                    title="能耗 (kWh)"
                    value={selectedDevice.energyConsumption}
                    precision={1}
                  />
                </Col>
              )}
              {selectedDevice.operatingHours && (
                <Col span={8}>
                  <Statistic
                    title="运行时长 (小时)"
                    value={selectedDevice.operatingHours}
                  />
                </Col>
              )}
            </Row>
            
            <Card title="基本信息" size="small" style={{ marginBottom: 16 }}>
              <Descriptions column={2} size="small">
                <Descriptions.Item label="设备名称">{selectedDevice.name}</Descriptions.Item>
                <Descriptions.Item label="设备类型">
                  {selectedDevice.type === 'elevator' ? '电梯' :
                   selectedDevice.type === 'hvac' ? '空调' :
                   selectedDevice.type === 'security' ? '安防' :
                   selectedDevice.type === 'lighting' ? '照明' :
                   selectedDevice.type === 'fire_safety' ? '消防' :
                   selectedDevice.type === 'access_control' ? '门禁' : selectedDevice.type}
                </Descriptions.Item>
                <Descriptions.Item label="所属楼宇">{selectedDevice.buildingName}</Descriptions.Item>
                <Descriptions.Item label="安装位置">{selectedDevice.location}</Descriptions.Item>
                <Descriptions.Item label="制造商">{selectedDevice.manufacturer}</Descriptions.Item>
                <Descriptions.Item label="设备型号">{selectedDevice.model}</Descriptions.Item>
              </Descriptions>
            </Card>
            
            <Card title="维护信息" size="small" style={{ marginBottom: 16 }}>
              <Descriptions column={2} size="small">
                <Descriptions.Item label="安装日期">{selectedDevice.installDate}</Descriptions.Item>
                <Descriptions.Item label="上次维护">{selectedDevice.lastMaintenance}</Descriptions.Item>
                <Descriptions.Item label="下次维护">{selectedDevice.nextMaintenance}</Descriptions.Item>
              </Descriptions>
            </Card>
            
            {selectedDevice.operatingHours && (
              <Card title="运行数据" size="small">
                <Row gutter={16}>
                  <Col span={12}>
                    <Progress
                      type="circle"
                      percent={Math.min((selectedDevice.operatingHours / 8760) * 100, 100)}
                      format={() => `${selectedDevice.operatingHours}h`}
                      size={80}
                    />
                    <div style={{ textAlign: 'center', marginTop: 8 }}>年度运行时长</div>
                  </Col>
                  {selectedDevice.energyConsumption && (
                    <Col span={12}>
                      <Progress
                        type="circle"
                        percent={Math.min((selectedDevice.energyConsumption / 1000) * 100, 100)}
                        format={() => `${selectedDevice.energyConsumption}kWh`}
                        size={80}
                        strokeColor="#52c41a"
                      />
                      <div style={{ textAlign: 'center', marginTop: 8 }}>能耗统计</div>
                    </Col>
                  )}
                </Row>
              </Card>
            )}
            
            <Card title="详细参数" size="small" style={{ marginTop: 16 }}>
              <Descriptions column={1} size="small">
                <Descriptions.Item label="设备ID">{selectedDevice.id}</Descriptions.Item>
                <Descriptions.Item label="楼宇ID">{selectedDevice.buildingId}</Descriptions.Item>
                <Descriptions.Item label="当前状态">
                  <Tag color={
                    selectedDevice.status === 'online' ? 'green' :
                    selectedDevice.status === 'maintenance' ? 'orange' :
                    selectedDevice.status === 'offline' ? 'red' : 'red'
                  }>
                    {selectedDevice.status === 'online' ? '正常运行' :
                     selectedDevice.status === 'maintenance' ? '维护模式' :
                     selectedDevice.status === 'offline' ? '设备离线' : '设备故障'}
                  </Tag>
                </Descriptions.Item>
              </Descriptions>
            </Card>
          </div>
        )}
      </Modal>

      {/* 楼宇详细信息模态框 */}
      <Modal
        title={
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <HomeOutlined />
            楼宇详细信息
          </div>
        }
        open={buildingModalVisible}
        onCancel={() => setBuildingModalVisible(false)}
        footer={null}
        width={900}
      >
        {selectedBuilding && (
          <div>
            <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
              <Col span={6}>
                <Statistic
                  title="楼宇状态"
                  value={selectedBuilding.status === 'normal' ? '正常' : 
                         selectedBuilding.status === 'medium' ? '中等' : '较低'}
                  valueStyle={{ 
                    color: selectedBuilding.status === 'normal' ? '#3f8600' : 
                           selectedBuilding.status === 'medium' ? '#cf1322' : '#cf1322'
                  }}
                  prefix={selectedBuilding.status === 'normal' ? <CheckCircleOutlined /> : 
                          <WarningOutlined />}
                />
              </Col>
              <Col span={6}>
                <Statistic
                  title="入住率"
                  value={selectedBuilding.occupancy}
                  suffix="%"
                  valueStyle={{ 
                    color: selectedBuilding.occupancy > 80 ? '#3f8600' : 
                           selectedBuilding.occupancy > 60 ? '#faad14' : '#cf1322'
                  }}
                />
              </Col>
              <Col span={6}>
                <Statistic
                  title="楼层数"
                  value={selectedBuilding.floors}
                  suffix="层"
                />
              </Col>
              <Col span={6}>
                <Statistic
                  title="电梯数量"
                  value={selectedBuilding.elevators.length}
                  suffix="部"
                />
              </Col>
            </Row>
            
            <Card title="基本信息" size="small" style={{ marginBottom: 16 }}>
              <Descriptions column={2} size="small">
                <Descriptions.Item label="楼宇名称">{selectedBuilding.name}</Descriptions.Item>
                <Descriptions.Item label="楼宇类型">
                  {selectedBuilding.type === 'residential' ? '住宅' :
                   selectedBuilding.type === 'commercial' ? '商业' :
                   selectedBuilding.type === 'office' ? '办公' :
                   selectedBuilding.type === 'mixed' ? '综合' : selectedBuilding.type}
                </Descriptions.Item>
                <Descriptions.Item label="楼宇ID">{selectedBuilding.id}</Descriptions.Item>
                <Descriptions.Item label="总楼层">{selectedBuilding.floors}层</Descriptions.Item>
                <Descriptions.Item label="入住率">{selectedBuilding.occupancy}%</Descriptions.Item>
                <Descriptions.Item label="运行状态">
                  <Tag color={
                    selectedBuilding.status === 'normal' ? 'green' :
                    selectedBuilding.status === 'medium' ? 'orange' : 'red'
                  }>
                    {selectedBuilding.status === 'normal' ? '正常运行' :
                     selectedBuilding.status === 'medium' ? '中等状态' : '需要关注'}
                  </Tag>
                </Descriptions.Item>
              </Descriptions>
            </Card>
            
            <Card title="电梯信息" size="small">
              <Table
                dataSource={selectedBuilding.elevators.map(elevator => ({
                  ...elevator,
                  key: elevator.id,
                  floorsText: `${elevator.floors[0]}-${elevator.floors[elevator.floors.length - 1]}层`
                }))}
                columns={[
                  {
                    title: '电梯编号',
                    dataIndex: 'id',
                    key: 'id',
                  },
                  {
                    title: '类型',
                    dataIndex: 'type',
                    key: 'type',
                    render: (type: string) => {
                      const typeMap = {
                        passenger: '客梯',
                        freight: '货梯',
                        emergency: '消防梯'
                      };
                      return typeMap[type as keyof typeof typeMap] || type;
                    }
                  },
                  {
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                    render: (status: string) => {
                      const statusConfig = {
                        normal: { color: 'green', text: '正常' },
                        maintenance: { color: 'orange', text: '维护中' },
                        error: { color: 'red', text: '故障' }
                      };
                      const config = statusConfig[status as keyof typeof statusConfig] || { color: 'default', text: status };
                      return <Tag color={config.color}>{config.text}</Tag>;
                    }
                  },
                  {
                    title: '服务楼层',
                    dataIndex: 'floorsText',
                    key: 'floorsText',
                  }
                ]}
                size="small"
                pagination={false}
              />
            </Card>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default Phase2View;